#include<string.h>
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>

//#define NUM 1024
//int main()
//{
//  umask(0);
//  const char* file_path = "./test.txt";
//  int fd = open(file_path, O_WRONLY | O_CREAT| 0666);
//  if(fd < 0) 
//  {
//    perror("open");
//    exit(1);
//  }
//  printf("open success!\n"); 
//  
//  const char* msg = "hello Mango\n";
//  write(fd,msg,strlen(msg)); //不写\0
//  printf("write success!\n");  
//  
//  lseek(fd,0,SEEK_SET);
//  printf("fd offset init success !\n");
//
//  char buf[NUM] = {0};
//  ssize_t n = read(fd,buf,sizeof(buf)-1);
//  if(n > 0)
//  {
//    buf[n-1] = '\0';
//    printf("%s\n",buf);
//  }
//  else 
//  {
//    perror("read:");
//    close(fd);
//    exit(2);
//  }
//
//  return 0;
//}
//

#define NUM 1024
int main()
{
  int read_fd = open("./old.txt",O_RDONLY);
  if(read_fd < 0)
  {
    perror("open:");
    exit(1);
  }
  printf("open old.txt success !\n");
  
  //umask(0);
  int write_fd = open("./New.txt",O_WRONLY | O_CREAT );
  chmod("./New.txt",0644);
  if(write_fd < 0)
  {
    perror("open:");
    exit(2);
  }
  printf("open New.txt success !\n");

  char buf[NUM] = {0};
  ssize_t ret = 0;
  while((ret = read(read_fd,buf,sizeof(buf))) > 0)
  {
    buf[ret-1] = '\0';
    printf("read from old.txt:%s\n",buf);
    write(write_fd,buf,sizeof(buf)-1);
  }
  close(write_fd);
  close(read_fd);
  return 0;
}
